home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1559 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  84 lines

  1. Path: lrz-muenchen.de!sun2!ua302aa
  2. From: ua302aa@sun2.lrz-muenchen.de (Kurt Watzka)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to access memory allocated in function
  5. Date: 15 Jan 1996 13:43:47 GMT
  6. Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
  7. Distribution: world
  8. Message-ID: <4ddlmj$av5@sparcserver.lrz-muenchen.de>
  9. References: <4ddbe3$so3@josie.abo.fi>
  10. NNTP-Posting-Host: sun2.lrz-muenchen.de
  11.  
  12. csundqvi@abo.fi (Christoffer Sundqvist) writes:
  13.  
  14. >Hello
  15.  
  16. >How can i access memory allocated dynamically in a function after i leave the 
  17. >function, something like this:
  18.  
  19. You cannot, because pointers are passed by value like all other objects
  20. in C.
  21.  
  22. >main()
  23. >{
  24. >int *p;
  25. >sub(p);
  26.  
  27. No prototype for sub() has been seen, so sub() will be called as 
  28. a function taking an unspecified number of parameters and returning
  29. int, i.e. as if sub() had been declared as "int sub();".
  30.  
  31. This may be a problem because sub does not return an int.
  32.  
  33. >}
  34.  
  35. >void sub(int *p)
  36. >{
  37. > p = malloc(.....);
  38. >}
  39.  
  40. If you want assigments to a variable passed to a function to have
  41. effect after the function returns, assigning to the function
  42. parameter is _not_ enough.
  43.  
  44. Two persons once wrote a book about C. In this book they state 
  45. that you should think about function parameters as conveniently
  46. initialized local variables of your function. Since the same
  47. two persons also "invented" the C programming language, maybe
  48. we should trust them.
  49.  
  50. Consider:
  51.  
  52.    void
  53.    sub(int n)
  54.    {
  55.       n = 4;
  56.    }
  57.  
  58.    main()
  59.    {
  60.       int m;
  61.  
  62.       sub(m);
  63.       return 0;
  64.    }
  65.  
  66. Would you expect m to be set to 4 after the call to sub()? This
  67. situation is very similar, if not identical, to the posted example.
  68.  
  69. The most common approaches to pass back a value from a function
  70. to the caller are
  71.  
  72.  1) return the value from the function or
  73.  2) pass a pointer to a variable to the function and let the 
  74.     function set that variable to the desired value.
  75.  
  76. The second method mimics "call by reference", as known from other
  77. languages.
  78.  
  79. Kurt
  80. --
  81. | Kurt Watzka                             Phone : +49-89-2180-6254
  82. | watzka@stat.uni-muenchen.de
  83. | ua302aa@sunmail.lrz-muenchen.de
  84.